package logic

import (
	"context"
	"github.com/18767156402/x/errors"
	"github.com/golang-module/carbon"
	"shortUrl/internal/model"
	"shortUrl/internal/svc"
	"shortUrl/internal/types"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type RedirectLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewRedirectLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RedirectLogic {
	return &RedirectLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *RedirectLogic) Redirect(req *types.RedirectReq) (resp *types.RedirectResp, err error) {

	var longUrl string
	var redirectCode int
	var ttl int64
	shortenLogic := NewShortenLogic(l.ctx, l.svcCtx)
	longUrl = shortenLogic.getShortUrlFromCache(req.ShortenKey)
	if longUrl == "" {
		var shortUrlModel model.ShortUrl
		result := l.svcCtx.Db.Model(&shortUrlModel).
			Where("shorten_key = ?", req.ShortenKey).Last(&shortUrlModel)
		if result.Error != nil {
			return nil, errors.New(1001, "获取短链失败")
		}
		longUrl = shortUrlModel.LongUrl
		redirectCode = shortUrlModel.RedirectCode

		if shortUrlModel.ExpireAt != nil {
			ttl = carbon.Now().DiffInSeconds(carbon.FromStdTime(*shortUrlModel.ExpireAt))
			if ttl <= 0 {
				redirectCode = 404
			}
		} else {
			//如果是永久的 则设置临时缓存是 1小时
			ttl = 3600
		}

		if ttl > 0 {
			shortenLogic.syncToCache(req.ShortenKey, longUrl, redirectCode, time.Duration(ttl)*time.Second)
		}

	} else {
		redirectCode = shortenLogic.getRedirectCodeFromCache(req.ShortenKey)
	}
	return &types.RedirectResp{
		LongUrl:      longUrl,
		RedirectCode: redirectCode,
	}, nil
}
